package com.da.lon.wang.xlg.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.appkefu.lib.interfaces.KFAPIs;
import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.CartNubBean;
import com.da.lon.wang.xlg.bean.DetailBean;
import com.da.lon.wang.xlg.bean.DetailBean.NomeList.Value;
import com.da.lon.wang.xlg.bean.DetailListBean;
import com.da.lon.wang.xlg.bean.IdsBean;
import com.da.lon.wang.xlg.bean.OrderListBean;
import com.da.lon.wang.xlg.bean.ZanBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.AnimationUtil;
import com.da.lon.wang.xlg.util.BuyUtil;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.SingleManager;
import com.da.lon.wang.xlg.util.ToastUtils;
import com.da.lon.wang.xlg.util.Utils;
import com.da.lon.wang.xlg.util.WebViewUtil;
import com.da.lon.wang.xlg.util.WebViewUtil.OnLoading;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.da.lon.wang.xlg.view.CancelPopWindow;
import com.da.lon.wang.xlg.view.LoadingDialog;
import com.da.lon.wang.xlg.view.McoyProductContentPage;
import com.da.lon.wang.xlg.view.McoyProductDetailInfoPage;
import com.da.lon.wang.xlg.view.McoySnapPageLayout;
import com.da.lon.wang.xlg.view.MyViewPager;
import com.da.lon.wang.xlg.view.ProductsPopupWindow;
import com.da.lon.wang.xlg.view.ProductsPopupWindow.CallBack3;
import com.da.lon.wang.xlg.view.ProductsShowMessagesPopupWindow;
import com.da.lon.wang.xlg.view.QuestionPopupWindow;
import com.da.lon.wang.xlg.view.ScrollWebView;
import com.jauker.widget.BadgeView;
import com.osell.selection.util.DeviceUuidFactory;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;


public class ProductsActivity extends FragmentActivity implements
        OnClickListener, CallBack3 {

    protected static final int MSG_SET_ALIAS = 0;
    private HttpLoader<DetailListBean> loader;
    private HttpLoader<OrderListBean> loader3;
    private DetailBean bean = new DetailBean();
    private HttpLoader<ZanBean> loader4;
    private HttpLoader<CartNubBean> loader5;
    private HttpLoader<IdsBean> loader6;

    private McoySnapPageLayout mcoySnapPageLayout = null;
    private McoyProductContentPage bottomPage = null;
    private McoyProductDetailInfoPage topPage = null;

    private static int width = 0;
    private ProductsPopupWindow contentWindow;
    private QuestionPopupWindow questionWindow;
    private CancelPopWindow cancelPopWindow;
    private ProductsShowMessagesPopupWindow productsShowMessagesPopupWindow;
    private View view;
    private Context context;

    private String product_number;
    private TextView detailView1, detailView2, detailView3;

    private ImageView img_line;

    private MyViewPager pager;
    private ImageView[] tips;
    public int index = 1;
    String user_id = MyApplication.getUserId();
    String device_id = MyApplication.getDeviceId();
    ImageView aniImage;
    int min = 1;
    long start = System.currentTimeMillis();


    private int select_color;
    private int unselect_color;

    private int mScreen1_4;
    final long end = start + min * 60 * 1000;
    private LinearLayout popupwindowLayout;
    private Button buyButton;
    private ImageView imageView;
    private LinearLayout topLayout;
    private ScrollWebView one_webview;


    private int isBuy = 0;
    private LoadingDialog dialog;
    private ImageButton backButton, smileButton, ringButton, shareButton;
    private TextView collectBox;
    private LinearLayout ouka_product_ll;
    private Timer timer;
    private TextView cartView;
    private Button addcartButton;
    private BadgeView badgeView;
    private long copy_time;

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        if (width == 0) {
            WindowManager manager = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            Display display = manager.getDefaultDisplay();
            width = display.getWidth();
        }
        return width;
    }

    /**
     * 咨询人工客服
     */
    public static void startChat(Context context, String storecode,
                                 String storename, String useraccount, String usernickname,
                                 String goodsImageurl, String goodstitledetail, String goodsprice,
                                 String goodsurl) {

        boolean isEcChat = true;

        if (TextUtils.isEmpty(storecode)) {
            storecode = "pxokakfq";
        }
        if (TextUtils.isEmpty(storename)) {
            storename = "客服对话";
        }
        if (TextUtils.isEmpty(useraccount)) {
            useraccount = "游客";
        }
        if (TextUtils.isEmpty(usernickname)) {
            usernickname = "游客";
        }
        if (TextUtils.isEmpty(goodsImageurl)) {
            isEcChat = false;
        }
        if (TextUtils.isEmpty(goodstitledetail)) {
            isEcChat = false;
        }
        if (TextUtils.isEmpty(goodsprice)) {
            isEcChat = false;
        }
        if (TextUtils.isEmpty(goodsurl)) {
            isEcChat = false;
        }

        KFAPIs.setTagNickname(usernickname + "(" + useraccount + ")", context);
        if (!isEcChat) {
            KFAPIs.startChat(context, storecode, // 1.

                    storename,
                    null,

                    false,
                    5, // 5.
                    null, // 6.
                    null, // 7.
                    false, // 8.
                    isEcChat, null);
        } else {
            KFAPIs.startECChat(context, storecode, // 1.

                    storename, //
                    goodsurl,
                    false,
                    5, //
                    null, //
                    null, //
                    false, //

                    true, //
                    goodsImageurl,
                    goodstitledetail,
                    goodsprice,

                    goodsurl, goodsurl, isEcChat, null);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUserInfoSp = MyApplication.getInstance().getSharedPreferences("user_info", Context.MODE_PRIVATE);

        setContentView(R.layout.ouka_products_main);
        try {
            Utils.setBasicUI(this);
        } catch (Exception e) {
        }
        ouka_product_ll = (LinearLayout) findViewById(R.id.ouka_product_ll);
        buyButton = (Button) findViewById(R.id.ouka_products_bottom);
        backButton = (ImageButton) findViewById(R.id.detail_back);
        smileButton = (ImageButton) findViewById(R.id.detail_smile);
        ringButton = (ImageButton) findViewById(R.id.detail_ring);
        shareButton = (ImageButton) findViewById(R.id.detail_share);

        collectBox = (TextView) findViewById(R.id.ouka_products_collect);
        cartView = (TextView) findViewById(R.id.ouka_products_cart);
        addcartButton = (Button) findViewById(R.id.ouka_products_addcart);

        aniImage = new ImageView(this);
        aniImage.setScaleType(ScaleType.FIT_XY);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50, 60);
        params.setMargins(0, -80, 0, 0);
        aniImage.setLayoutParams(params);
        ouka_product_ll.addView(aniImage);
        aniImage.setVisibility(View.GONE);

        cartView.setOnClickListener(this);
        addcartButton.setOnClickListener(this);
        collectBox.setOnClickListener(this);

        buyButton.setOnClickListener(this);
        backButton.setOnClickListener(this);
        smileButton.setOnClickListener(this);
        ringButton.setOnClickListener(this);
        shareButton.setOnClickListener(this);

        topLayout = (LinearLayout) findViewById(R.id.detail_top);
        topLayout.bringToFront();

        context = this;
        PreferenceUtils.getInstance().SetSettingString(
                PreferencesConfig.COUNT_NUMBER, "1");

        dialog = new LoadingDialog(ProductsActivity.this);
        product_number = PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.PRODUCT_NUMBER, "");
        if (TextUtils.isEmpty(product_number)) {
            product_number = getIntent().getStringExtra("product_number");
        }
        badgeView = new BadgeView(context);
        badgeView.setTargetView(cartView);
        init();

    }

    /**
     * 初始化界面
     */
    private void initView() {
        mcoySnapPageLayout = (McoySnapPageLayout) findViewById(R.id.products_layout);
        topPage = new McoyProductDetailInfoPage(ProductsActivity.this,
                getcontentview());
        bottomPage = new McoyProductContentPage(ProductsActivity.this,
                getdetailview());
        mcoySnapPageLayout.setSnapPages(topPage, bottomPage);
    }

    private View getdetailview() {
        try {
            view = this.getLayoutInflater().inflate(
                    R.layout.ouka_products_detail, null);
            select_color = getResources().getColor(R.color.ouka_red);
            one_webview = (ScrollWebView) view.findViewById(R.id.one_webview);
            unselect_color = getResources().getColor(R.color.ouka_black);
            detailView1 = (TextView) view.findViewById(R.id.detailbutton1);
            detailView2 = (TextView) view.findViewById(R.id.detailbutton2);
            detailView3 = (TextView) view.findViewById(R.id.detailbutton3);
            img_line = (ImageView) view.findViewById(R.id.img_line);
            mScreen1_4 = getScreenWidth(this) / 3;
            LayoutParams lp = img_line.getLayoutParams();
            lp.width = mScreen1_4;
            img_line.setLayoutParams(lp);
            detailView1.setOnClickListener(new MyOnClickListenser());
            detailView2.setOnClickListener(new MyOnClickListenser());
            detailView3.setOnClickListener(new MyOnClickListenser());
            one_webview.getSettings().setUseWideViewPort(true);
            one_webview.getSettings().setLoadWithOverviewMode(true);
            one_webview.getSettings().setBuiltInZoomControls(false);
            one_webview.getSettings().setJavaScriptEnabled(true);
            WebViewUtil util = new WebViewUtil(context);
            util.setWebView(
                    Utils.constructUrl(XLGConstants.WEB_URL + "p/"
                            + product_number + ".html?viewtype=1&"), null,
                    one_webview, 0);
            util.setOnloadingListener(new OnLoading() {

                @Override
                public void onStart(String url) {

                }

                @Override
                public void onGetLocation(String url) {

                }

                @Override
                public void onError() {

                }

                @Override
                public void onComplete(String url) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        return view;
    }

    /**
     * 更新购物车数量
     */
    private void initCart() {

        try {

            loader5 = new HttpLoader<CartNubBean>(context, XLGConstants.URL
                    + "/Cart-cartcount", CartNubBean.class, 60 * 1000);
            AjaxParams params = new AjaxParams();
            params.put("id", mUserInfoSp.getString("user_id", ""));
            params.put("deviceId", new DeviceUuidFactory(this).getDeviceUuid().toString());
            params.put("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%"
                    + "cartcount"));
            loader5.setManagerListener(new OnWebLoadListener<CartNubBean>() {

                @Override
                public void OnStart() {
                }

                @Override
                public void OnError(String error) {
                }

                @Override
                public void onSuccess(CartNubBean t) {
                    if (t != null && t.getCode().equals("000000")) {

                        if (t.getResult().equals("0")) {
                            badgeView.setVisibility(View.GONE);
                        } else {
                            String re = t.getResult() != null ? t.getResult()
                                    : "0";
                            badgeView.setBadgeCount(Integer.parseInt(re));
                        }
                    }
                }
            });

            loader5.loadData(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setImageBackground(ImageView[] tips, int selectItems) {
        for (int i = 0; tips != null && i < tips.length; i++) {
            if (i == selectItems) {
                tips[i].setImageResource(R.drawable.tip_foucsed);
            } else {
                tips[i].setImageResource(R.drawable.tip_unfoucsed);
            }
        }
    }

    protected SharedPreferences mUserInfoSp;

    private void init() {

        try {
            product_number = PreferenceUtils.getInstance().getSettingStr(
                    PreferencesConfig.PRODUCT_NUMBER, "");

            if (TextUtils.isEmpty(product_number)) {
                product_number = getIntent().getStringExtra("product_number");
            }
            loader = new HttpLoader<DetailListBean>(context, XLGConstants.URL
                    + "/Product-details", DetailListBean.class, 60 * 1000);
            AjaxParams params = new AjaxParams();

            params.put("product_number", product_number);
            params.put("token", XLGDataUtils.encrypt2MD5("Product" + "2015#$%"
                    + "details"));
            params.put("type", "2");
            params.put("id", mUserInfoSp.getString("user_id", ""));
            params.put("user_key", mUserInfoSp.getString("user_key", ""));
            params.put("fr", "shop");

            loader.setManagerListener(new OnWebLoadListener<DetailListBean>() {

                @Override
                public void OnStart() {
                    if (!ProductsActivity.this.isFinishing() && dialog != null
                            && !dialog.isShowing()) {
                        dialog.show();
                    }

                }

                @Override
                public void OnError(String error) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }

                @Override
                public void onSuccess(DetailListBean t) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    if (t != null && t.getCode().equals("000000")) {
                        bean = t.getResult();
                        String is_collect = bean.getCollcount();
                        // 判断收藏
                        if (is_collect.equals("")) {
                            Drawable drawable = getResources().getDrawable(
                                    R.drawable.ocoffee_collect_normal);
                            drawable.setBounds(0, 0,
                                    drawable.getMinimumWidth(),
                                    drawable.getMinimumHeight());
                            collectBox.setCompoundDrawables(null, drawable,
                                    null, null);
                        } else {
                            if (is_collect.equals("1")) {
                                Drawable drawable = getResources().getDrawable(
                                        R.drawable.ocoffee_collect_pressed);
                                drawable.setBounds(0, 0,
                                        drawable.getMinimumWidth(),
                                        drawable.getMinimumHeight());
                                collectBox.setCompoundDrawables(null, drawable,
                                        null, null);
                            } else {
                                Drawable drawable = getResources().getDrawable(
                                        R.drawable.ocoffee_collect_normal);
                                drawable.setBounds(0, 0,
                                        drawable.getMinimumWidth(),
                                        drawable.getMinimumHeight());
                                collectBox.setCompoundDrawables(null, drawable,
                                        null, null);
                            }
                        }
                        initView();
                        if (!bean.getIsdown().equals("")) {
                            String isdown = bean.getIsdown() != null ? bean
                                    .getIsdown() : "0";
                            if (Integer.parseInt(isdown) == 0) {
                                // 商品下架
                                popupwindowLayout.setClickable(false);
                                buyButton.setClickable(false);
                                buyButton.setBackgroundColor(Color
                                        .parseColor("#bfbfbf"));
                                addcartButton.setClickable(false);
                                addcartButton.setBackgroundColor(Color
                                        .parseColor("#FFC3C5"));
                            }
                        }
                        String Is_display = bean.getIs_display() != null ? bean
                                .getIs_display() : "0";
                        if (!"".equals(Is_display)
                                && Integer.parseInt(Is_display) == 0) {
                            // 咖啡流程
                            addcartButton.setVisibility(View.GONE);
                        }
                        // 秒杀流程
                        if (bean.getMs() != null) {
                            if (bean.getMs().getE_time() > 0
                                    && bean.getMs().getS_time() == 0) {
                                // 此商品参数秒杀，并且正式秒杀活动时间内
                                addcartButton.setVisibility(View.GONE);
                                buyButton.setText("立即秒杀");
                                // beginTimer(bean.getMs().getE_time());
                            } else if (bean.getMs().getE_time() == 0
                                    && bean.getMs().getS_time() > 0) {
                                // beginTimer(bean.getMs().getS_time());
                            }
                        }
                    } else {
                        ToastUtils.showShort(context, t.getMessage());
                    }
                }
            });

            loader.loadData(params);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @SuppressWarnings("deprecation")
    private View getcontentview() {
        try {
            view = this.getLayoutInflater().inflate(
                    R.layout.ouka_products_content, null);
            pager = (MyViewPager) view.findViewById(R.id.detail_viewpager);
            ViewGroup group = (ViewGroup) view.findViewById(R.id.detail_dot_ll);
            if (bean.getGallery_img() != null
                    && bean.getGallery_img().size() > 0) {
                String[] imgurl = new String[bean.getGallery_img().size()];
                MyApplication.loadImageByPicasso(context, bean.getGallery_img()
                        .get(0).getImg_url(), null, aniImage, 60, 60, 0);

                for (int i = 0; i < bean.getGallery_img().size(); i++) {
                    imgurl[i] = bean.getGallery_img().get(i).getImg_url();
                }

                tips = new ImageView[imgurl.length];
                for (int i = 0; i < tips.length; i++) {
                    ImageView imageView = new ImageView(context);
                    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                            20, 20);
                    param.setMargins(5, 0, 5, 0);
                    imageView.setLayoutParams(param);
                    tips[i] = imageView;
                    if (i == 0) {
                        tips[i].setImageResource(R.drawable.tip_foucsed);
                    } else {
                        tips[i].setImageResource(R.drawable.tip_unfoucsed);
                    }

                    group.addView(imageView);
                }
                view.setTag(tips);

                pager.setAdapter(new ImagePagerAdapter(context, imgurl));
            }
            pager.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    setImageBackground(tips, arg0);
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {

                }
            });

            TextView nameView = (TextView) view.findViewById(R.id.detail_name);
            LinearLayout xiadan_ll = (LinearLayout) view.findViewById(R.id.xiadan_ll);
            TextView subnameView = (TextView) view
                    .findViewById(R.id.detail_sub_name);
            TextView priceView = (TextView) view
                    .findViewById(R.id.detail_price);
            TextView pricespeView = (TextView) view
                    .findViewById(R.id.detail_pricespe);
            TextView salesView = (TextView) view
                    .findViewById(R.id.detail_sales);
            TextView typeView = (TextView) view.findViewById(R.id.detail_type);
            TextView nomenameView = (TextView) view
                    .findViewById(R.id.detail_nomename);
            //折扣率
            TextView order_product_zkl_tv = (TextView) view
                    .findViewById(R.id.order_product_zkl_tv);
            TextView countryView = (TextView) view
                    .findViewById(R.id.detail_country);
            ImageView questionView = (ImageView) view
                    .findViewById(R.id.detail_question);
            LinearLayout questionLayout = (LinearLayout) view
                    .findViewById(R.id.detail_type_question);
            ImageView flagView = (ImageView) view
                    .findViewById(R.id.detail_countryflag);
            ImageView soldoutView = (ImageView) view
                    .findViewById(R.id.detail_products_soldout);
            popupwindowLayout = (LinearLayout) view
                    .findViewById(R.id.ouka_products_popupwindow);

            if (!bean.getIsdown().equals("")) {
                String isdown = bean.getIsdown() != null ? bean.getIsdown()
                        : "0";
                if (Integer.parseInt(isdown) == 0) {
                    soldoutView.setVisibility(View.VISIBLE);
                }
            }

            LinearLayout cancelLayout = (LinearLayout) view
                    .findViewById(R.id.products_cancel_popupwindow);
            cancelLayout.setOnClickListener(this);

            TextView tv_product_supplier_name = view.findViewById(R.id.tv_product_supplier_name);

            nameView.setText(bean.getName());
            subnameView.setText(bean.getSub_title());
            tv_product_supplier_name.setText(bean.getStoreName());


            // 秒杀价格
            if (bean.getMs() != null && bean.getMs().getE_time() != 0
                    && bean.getMs().getS_time() == 0) {
                priceView.setText("秒杀价:" + bean.getPrice_symbol() + bean.getMs().getSeckill_price());
            } else {
                priceView.setText(bean.getPrice_symbol() + bean.getSeal_price());
            }
            // 折扣率
            if (bean.getZkl() > 0) {
                order_product_zkl_tv.setText(bean.getZkl() + "折");
            } else {
                xiadan_ll.setVisibility(View.GONE);
            }

            pricespeView.setText(bean.getPrice_symbol() + bean.getPrice() + "/"
                    + bean.getMeasure());
            pricespeView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            salesView.setText("销量" + bean.getSales() + "件");
            nomenameView.setText(bean.getNomename());
            countryView.setText("产地:" + bean.getCoutryname());
            MyApplication.loadImageByPicasso(context, bean.getFlag_img(), null,
                    flagView, 0, 0, 1);
            String ty = bean.getPro_type_id() != null ? bean.getPro_type_id()
                    : "0";
            int type = Integer.parseInt(ty);
            if (type > 0) {
                typeView.setText("税费:" + bean.getRateprice());
            } else {
                typeView.setText("税费:" + "完税");
            }

            // 点击选择数量
            popupwindowLayout.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (contentWindow != null && contentWindow.isShowing()) {
                        contentWindow.dismiss();
                    }
                    // 实例化SelectPicPopupWindow
                    contentWindow = new ProductsPopupWindow(context, bean, 0,
                            ProductsActivity.this, popupwindowLayout);
                    // 显示窗口
                    contentWindow.showAtLocation(popupwindowLayout,
                            Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        // view.invalidate();
        return view;
    }

    /**
     * 点击购物车 显示抛物线
     */
    private void showAnimition() {
        try {
            float[][] points = new float[3][2];

            int[] cartViewLocation = new int[2];
            cartView.getLocationOnScreen(cartViewLocation);
            int[] addcartButtonLocation = new int[2];
            addcartButton.getLocationOnScreen(addcartButtonLocation);
            int aniImageWith = aniImage.getWidth();
            float[] p1 = new float[]{
                    cartViewLocation[0]
                            + ((cartView.getWidth() - aniImageWith) / 2), 0};

            float[] p3 = new float[]{
                    addcartButtonLocation[0]
                            + ((addcartButton.getWidth() - aniImageWith) / 2),
                    0};

            float[] p2 = new float[]{(p1[0] + p3[0]) / 2, 300};
            points[0] = p1;
            points[1] = p2;
            points[2] = p3;
            AnimationUtil.startAnimation(aniImage, points, addcartButton);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {

        try {

            Intent intent = null;
            switch (v.getId()) {
                // 立即购买
                case R.id.ouka_products_bottom:
                    String Is_display = bean.getIs_display() != null ? bean
                            .getIs_display() : "0";
                    if (!"".equals(Is_display) && Integer.parseInt(Is_display) == 0) {
                        // 咖啡特殊商品 咖啡秒杀没有写
                        BuyUtil util = new BuyUtil(this);
                        String pid = bean.getId();
                        String value = "";
                        String attr = "";
                        int[] mySelect = SingleManager.getInstance().getMap(pid);
                        if (bean != null && bean.getNome_list() != null
                                && bean.getNome_list().size() == 0) {
                            value = "{}";
                        } else if (mySelect != null) {
                            value = getCartValue(mySelect);
                            attr = getValue(mySelect);
                        }
                        if (null != bean.getFhname()
                                && null != bean.getFhname().get(0)
                                && null != bean.getFhname().get(0)
                                .getSend_mothed_id()) {
                            util.buyClick(pid, value, attr, true, bean.getFhname()
                                            .get(0).getSend_mothed_id(), null, null, null,
                                    this);
                        } else {
                            ToastUtils.showShort(context, "亲，配送方式异常，请稍后再试`!");
                        }
                    } else {
                        // 普通商品
                        contentWindow = new ProductsPopupWindow(context, bean, 0,
                                ProductsActivity.this, popupwindowLayout);
                        // 显示窗口
                        contentWindow.showAtLocation(popupwindowLayout,
                                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    }

                    break;
                case R.id.detail_back:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    finish();
                    break;
                case R.id.detail_smile:

                    try

                    {
                        String storecode = "";
                        String storename = "";
                        String useraccount = "";
                        String usernickname = "";
                        String goodsImageurl = bean.getBigimage();
                        String goodstitledetail = bean.getName();
                        String goodsprice = bean.getPricespe() + "";
                        String goodsurl = bean.getUrl();
                        startChat(context, storecode, storename, useraccount,
                                usernickname, goodsImageurl, goodstitledetail,
                                goodsprice, goodsurl);
                    } catch (Exception e) {

                        Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT).show();
                    }

                    break;
                case R.id.detail_ring:

                    String user_key = MyApplication.getUserKey();
                    if (TextUtils.isEmpty(user_key)) {
                        intent = new Intent(context, LoginActivity.class);
                    } else {
                        intent = new Intent(context, WebViewActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putInt("flag", 001);
                        bundle.putString("url", XLGConstants.WEB_URL
                                + "Message-index.html");
                        intent.putExtras(bundle);
                    }
                    startActivity(intent);

                    break;
                case R.id.detail_share:

                    if (null != bean) {
                        Utils.showShare(context, bean.getName(),
                                bean.getShare_info(), bean.getUrl(),
                                bean.getShare_img());
                    }

                    break;

                case R.id.ouka_products_cart:
                    if (MyApplication.isNetworkAvailable(context)) {
                        intent = new Intent(ProductsActivity.this,
                                CartActivity.class);
                        startActivity(intent);
                    }
                    break;

                // 加入购物车
                case R.id.ouka_products_addcart:
                    contentWindow = new ProductsPopupWindow(context, bean, 1,
                            ProductsActivity.this, popupwindowLayout);
                    // 显示窗口
                    contentWindow.showAtLocation(popupwindowLayout, Gravity.BOTTOM
                            | Gravity.CENTER_HORIZONTAL, 0, 0);

                    break;

                case R.id.ouka_products_collect:

                    initCollect();

                    break;

                // 退货广告popwindow
                case R.id.products_cancel_popupwindow:
                    if (cancelPopWindow != null && cancelPopWindow.isShowing()) {
                        cancelPopWindow.dismiss();
                    }
                    // 实例化SelectPicPopupWindow
                    cancelPopWindow = new CancelPopWindow(this);
                    // 显示窗口
                    if (popupwindowLayout != null) {
                        cancelPopWindow.showAtLocation(popupwindowLayout,
                                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    }

                    break;

                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initCollect() {

        try {

            if (TextUtils.isEmpty(MyApplication.getUserKey())) {
                Intent intent11 = new Intent(context, LoginActivity.class);
                intent11.putExtra("isGotoHome", false);
                startActivityForResult(intent11, 300);
            } else {
                loader4 = new HttpLoader<ZanBean>(context, XLGConstants.URL
                        + "/index-singproduct", ZanBean.class, 60 * 1000);
                AjaxParams params11 = new AjaxParams();
                params11.put("token", XLGDataUtils.encrypt2MD5("index"
                        + "2015#$%" + "singproduct"));
                params11.put("id", mUserInfoSp.getString("user_id", ""));
                params11.put("user_key", mUserInfoSp.getString("user_key", ""));
                params11.put("pid", bean.getId());
                params11.put("type", "0");
                loader4.setManagerListener(new OnWebLoadListener<ZanBean>() {

                    @Override
                    public void OnStart() {
                        if (dialog != null && !dialog.isShowing()) {
                            dialog.show();
                        }

                    }

                    @Override
                    public void OnError(String error) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onSuccess(ZanBean t) {
                        if (dialog != null) {
                            dialog.dismiss();
                        }
                        if (t != null && t.getCode().equals("000000")) {
                            if (t.getResult().getLike().equals("1")) {
                                Drawable drawable = getResources().getDrawable(
                                        R.drawable.ocoffee_collect_pressed);
                                drawable.setBounds(0, 0,
                                        drawable.getMinimumWidth(),
                                        drawable.getMinimumHeight());
                                collectBox.setCompoundDrawables(null, drawable,
                                        null, null);
                            } else {
                                Drawable drawable = getResources().getDrawable(
                                        R.drawable.ocoffee_collect_normal);
                                drawable.setBounds(0, 0,
                                        drawable.getMinimumWidth(),
                                        drawable.getMinimumHeight());
                                collectBox.setCompoundDrawables(null, drawable,
                                        null, null);
                            }

                        }
                    }
                });

                loader4.loadData(params11);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public String getValue(int[] selected) {
        String parm1 = "";
        try {
            List<MyValue> myValues = new ArrayList<MyValue>();
            for (int i = 0; null != bean.getNome_list() && selected != null
                    && i < selected.length; i++) {
                MyValue mvalue = new MyValue();
                mvalue.name = bean.getName();
                int index = selected[i];
                Value va = bean.getNome_list().get(i).getValue().get(index);
                mvalue.value = va.getAttr_value();
                mvalue.values_all = va.getValues_all();
                myValues.add(mvalue);
            }
            for (int i = 0; myValues != null && i < myValues.size(); i++) {
                MyValue value = myValues.get(i);
                parm1 = parm1 + value.values_all + ",";
            }
            if (parm1.length() > 0) {
                parm1 = parm1.substring(0, parm1.length() - 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return parm1;
    }

    public String getCartValue(int[] selected) {
        String parm2 = "";
        try {
            List<MyValue> myValues = new ArrayList<MyValue>();
            for (int i = 0; null != bean.getNome_list() && selected != null
                    && i < selected.length; i++) {
                MyValue mvalue = new MyValue();
                mvalue.name = bean.getNome_list().get(i).getName();
                int index = selected[i];
                Value va = bean.getNome_list().get(i).getValue().get(index);
                mvalue.value = va.getAttr_value();
                mvalue.values_all = va.getValues_all();
                myValues.add(mvalue);
            }
            parm2 = "{";
            for (int i = 0; myValues != null && i < myValues.size(); i++) {
                MyValue value = myValues.get(i);
                parm2 = parm2 + "\"" + i + "\"" + ":{" + "\"name\":" + "\""
                        + value.name + "\"" + "," + "\"value\":\""
                        + value.value + "\"},";
            }
            if (parm2.length() > 0) {
                parm2 = parm2.substring(0, parm2.length() - 1);
                parm2 = parm2 + "}";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return parm2;
    }

    /**
     * 添加商品到购物车
     *
     * @param send_address_id 发货ID
     */

    protected void addCart(String send_address_id,
                           final PopupWindow product_popupWindow) {
        SingleManager manager11 = SingleManager.getInstance();
        final int[] mySelect11 = manager11.getMap(bean.getId());
        String count11 = PreferenceUtils.getInstance().getSettingStr(
                PreferencesConfig.COUNT_NUMBER, "");

        loader3 = new HttpLoader<OrderListBean>(this, XLGConstants.URL
                + "Cart-AjaxAdd", OrderListBean.class, 60 * 1000);

        AjaxParams params1 = new AjaxParams();

        params1.put("token", XLGDataUtils.encrypt2MD5("Cart" + "2015#$%"
                + "AjaxAdd"));
        params1.put("id", mUserInfoSp.getString("user_id", ""));
        params1.put("deviceId", new DeviceUuidFactory(this).getDeviceUuid().toString());
        params1.put("pid", bean.getId());
        params1.put("type", "2");
        params1.put("count", count11);
        params1.put("fhtype", send_address_id);

        if (bean.getNome_list().size() == 0) {
            params1.put("value", "{}");
            loader3.loadData(params1);
        } else {
            if (mySelect11 != null) {
                params1.put("value", getCartValue(mySelect11));
                params1.put("products_model_attr", getValue(mySelect11));
                loader3.loadData(params1);
            } else {
                Toast.makeText(ProductsActivity.this, "请先选择属性",
                        Toast.LENGTH_SHORT).show();
            }
        }

        loader3.setManagerListener(new OnWebLoadListener<OrderListBean>() {

            @Override
            public void OnStart() {
                if (dialog != null && !dialog.isShowing()) {
                    dialog.show();
                }
            }

            @Override
            public void OnError(String error) {
                if (dialog != null) {
                    dialog.dismiss();
                }
            }

            @Override
            public void onSuccess(OrderListBean t) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                if (t != null && t.getCode().equals("000000")) {
                    ToastUtils.showShort(context, "已加到购物车，赶快去结算吧！");
                    // showAnimition();
                    initCart();
                    product_popupWindow.dismiss();
                } else if ((t != null && t.getCode().equals("000002"))
                        && t.getMessage().contains("库存不足")) {
                    if (productsShowMessagesPopupWindow != null
                            && productsShowMessagesPopupWindow.isShowing()) {
                        productsShowMessagesPopupWindow.dismiss();
                    }
                    productsShowMessagesPopupWindow = new ProductsShowMessagesPopupWindow(
                            context, bean.getKefu_phone(),
                            ProductsActivity.this);
                    // 显示窗口
                    productsShowMessagesPopupWindow.showAtLocation(
                            popupwindowLayout, Gravity.CENTER
                                    | Gravity.CENTER_HORIZONTAL, 0, 0);
                } else {
                    ToastUtils.showShort(ProductsActivity.this, t.getMessage());
                }
            }
        });
    }

    public class MyOnClickListenser implements OnClickListener {

        @Override
        public void onClick(View v) {
            resetTextColor();
            switch (v.getId()) {
                case R.id.detailbutton1:
                    detailView1.setTextColor(select_color);
                    one_webview.loadUrl(Utils.constructUrl(XLGConstants.WEB_URL
                            + "p/" + product_number + ".html?viewtype=1&"));
                    break;
                case R.id.detailbutton3:
                    detailView3.setTextColor(select_color);
                    one_webview.loadUrl(Utils.constructUrl(XLGConstants.WEB_URL
                            + "p/" + product_number + ".html?viewtype=2&"));
                    break;
                case R.id.detailbutton2:
                    detailView2.setTextColor(select_color);
                    one_webview.loadUrl(Utils.constructUrl(XLGConstants.WEB_URL
                            + "p/" + product_number + ".html?viewtype=3&"));
                    break;
            }
        }
    }

    private void resetTextColor() {
        detailView1.setTextColor(unselect_color);
        detailView2.setTextColor(unselect_color);
        detailView3.setTextColor(unselect_color);
    }

    private class MyValue {
        public String name;
        public String value;
        private String values_all;
    }

    @Override
    public void click(View v, String send_address_id,
                      PopupWindow product_popupWindow) {
        switch (v.getId()) {
            case R.id.ouka_products_addcart_bt:

                addCart(send_address_id, product_popupWindow);

                break;
            case R.id.online_custome_tv:

                try

                {
                    String storecode = "";
                    String storename = "";
                    String useraccount = "";
                    String usernickname = "";
                    String goodsImageurl = bean.getBigimage();
                    String goodstitledetail = bean.getName();
                    String goodsprice = bean.getPricespe() + "";
                    String goodsurl = bean.getUrl();
                    startChat(context, storecode, storename, useraccount,
                            usernickname, goodsImageurl, goodstitledetail,
                            goodsprice, goodsurl);
                } catch (Exception e) {

                    Toast.makeText(context, "参数有误", Toast.LENGTH_SHORT).show();
                }

                break;

            default:
                break;
        }
    }

    private class ImagePagerAdapter extends PagerAdapter {

        private LayoutInflater inflater;
        private String[] urls;

        ImagePagerAdapter(Context context, String[] us) {

            inflater = LayoutInflater.from(ProductsActivity.this);
            this.urls = us;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            ((ViewPager) container).removeView((View) object);
        }

        @Override
        public void finishUpdate(View container) {
        }

        @Override
        public int getCount() {
            return urls != null ? urls.length : 0;
        }

        @Override
        public Object instantiateItem(ViewGroup view, final int position) {
            View imageLayout = null;
            try {
                imageLayout = inflater.inflate(R.layout.item_pager_image, view,
                        false);

                imageView = (ImageView) imageLayout.findViewById(R.id.image);

                imageView.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context,
                                ImagePreviewActivity.class);

                        Bundle bundle = new Bundle();
                        bundle.putStringArray("PHOTOES", urls);
                        bundle.putInt("position", position);
                        intent.putExtras(bundle);

                        context.startActivity(intent);
                    }
                });
                if (urls != null) {
                    MyApplication.loadImageByPicasso(context, urls[position],
                            null, imageView, 0, 0, 0);
                }
                ((ViewPager) view).addView(imageLayout, 0); // 将图片增加到ViewPager

            } catch (Exception e) {
                e.printStackTrace();
            }

            return imageLayout;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View container) {
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        initCart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        if (productsShowMessagesPopupWindow != null
                && productsShowMessagesPopupWindow.isShowing()) {
            productsShowMessagesPopupWindow.dismiss();
        }
        if (null != contentWindow && null != contentWindow.getUtil()) {
            contentWindow.getUtil().closeShowMessagesPopupWindow();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (productsShowMessagesPopupWindow != null
                && productsShowMessagesPopupWindow.isShowing()) {
            productsShowMessagesPopupWindow.dismiss();
        }
        if (null != contentWindow && null != contentWindow.getUtil()) {
            contentWindow.getUtil().closeShowMessagesPopupWindow();
        }
    }
}
